import 'package:base_lib/common/base/base_bloc_page.dart';
import 'package:base_lib/index.dart';
import 'package:common_lib/common_compoent.dart';
import 'package:common_lib/patient_management/patient_list/patient_list_bloc.dart';
import 'package:flutter/cupertino.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:flutter/material.dart';

class PatientListPage extends BaseBlocPage<PatientListBloc, _PatientListState> {
  PatientListPage(Parameters parameters) : super(parameters);

  @override
  _PatientListState generateThemeState() {
    return _PatientListState();
  }
}

class _PatientListState extends BaseBlocPageState<PatientListBloc> {
  String title = "";

  RefreshController _refreshController =
      RefreshController(initialRefresh: true);

  void initState() {
    super.initState();
    title = parameters.getString("title");

    // EventBus.instance.register("event11", null, (context, parameters) {

    // })
  }

  @override
  ignoreWindowWidget() => false;

  @override
  Widget buildChild(BuildContext context, MTheme theme) {
    return Scaffold(
      appBar: AppBar(title: Text(title), actions: <Widget>[
        IconButton(
            icon: Icon(Icons.search),
            onPressed: () {
              showSearch(context: context, delegate: SearchBar(bloc));
            }),
      ]),
      backgroundColor: Colors.white,
      body: Container(
        color: theme.themeColor.themeBgColor,
        child: Column(
          children: [
            Container(
              color: Colors.white,
              child: ListTile(
                title: Text("线下患者"),
                trailing: GestureDetector(
                  onTap: () {
                    bloc.jumpToAddPateintPage(context);
                  },
                  child: Image.asset(
                    "images/addPatient/patient_add.png",
                    package: CommonComponent.assetsPackageName,
                    width: 110.0,
                  ),
                ),
              ),
            ),
            Divider(height: 1),
            Expanded(
              child: StreamBuilder(
                stream: bloc.dataSourceSubject,
                initialData: [],
                builder: (context, snapshot) {
                  return snapshot.hasData
                      ? SmartRefresher(
                          enablePullDown: true,
                          enablePullUp: false,
                          header: WaterDropHeader(),
                          controller: _refreshController,
                          onRefresh: _onRefresh,
                          child: snapshot.data.length > 0
                              ? _cellBuilder(snapshot.data, bloc)
                              : Center(
                                  child: Text("请先添加线下患者"),
                                ))
                      : Container();
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _onRefresh() async {
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use refreshFailed()
    bloc.getDoctorAllPatient(() {
      _refreshController.refreshCompleted();
    }, () {
      _refreshController.refreshFailed();
    });
  }

  @override
  PatientListBloc generateBloc() {
    return PatientListBloc();
  }
}

class SearchBar extends SearchDelegate {
  final PatientListBloc bloc;
  SearchBar(this.bloc);

  //复写点击搜索框右侧图标方法,此方法也就是点击右侧图标的回调函数,点击右侧图标把搜索内容情空
  @override
  List<Widget> buildActions(BuildContext context) {
    // TODO: implement buildActions
    return [
      IconButton(
        icon: Icon(Icons.clear),
        //点击后清除搜索框内容
        onPressed: () => {query = ''},
      ),
    ];
  }

  //点击搜索框右侧的图标,案例这里放的是返回按钮
  @override
  Widget buildLeading(BuildContext context) {
    // TODO: implement buildLeading
    return IconButton(
      icon: AnimatedIcon(
        icon: AnimatedIcons.menu_arrow,
        progress: transitionAnimation,
      ),
      onPressed: () => close(context, null),
    );
  }

  //点击了搜索显示的页面
  @override
  Widget buildResults(BuildContext context) {
    return StreamBuilder(
        stream: bloc.searchDataSourceSubject,
        initialData: [],
        builder: (context, snapshot) {
          return _cellBuilder(snapshot.data, bloc);
        });
  }

  //提示性文字内容
  @override
  Widget buildSuggestions(BuildContext context) {
    bloc.getSearchPatientOfName(query);
    return StreamBuilder(
        stream: bloc.searchDataSourceSubject,
        initialData: [],
        builder: (context, snapshot) {
          return _cellBuilder(snapshot.data, bloc);
        });
  }
}

Widget _cellBuilder(list, bloc) {
  return ListView.separated(
    itemCount: list.length,
    separatorBuilder: (context, index) => Divider(height: .0),
    itemBuilder: (BuildContext context, int index) {
      return GestureDetector(
        onTap: () {
          bloc.selectedPatient(context, list[index]);
        },
        child: Container(
          color: Colors.white,
          padding: EdgeInsets.all(16),
          child: Row(
            children: [
              Expanded(
                flex: 1,
                child: Row(
                  children: [
                    Image.asset(
                      "images/public/public_avatar.png",
                      package: CommonComponent.assetsPackageName,
                      width: 50,
                      height: 50,
                    ),
                    Padding(
                        padding: EdgeInsets.only(left: 16),
                        child: Text(list[index].patientName,
                            style: TextStyle(fontSize: 16))),
                    Padding(
                        padding: EdgeInsets.only(left: 16),
                        child: Text(Utils.returnGenderByInt(list[index].sex),
                            style: TextStyle(fontSize: 16))),
                    Padding(
                        padding: EdgeInsets.only(left: 16),
                        child: Text(
                            DateUtil.returnAgeByBirthday(
                                DateUtil.getDateTime(list[index].birthDay)),
                            style: TextStyle(fontSize: 16))),
                  ],
                ),
              ),
              GestureDetector(
                onTap: () {
                  bloc.jumpToEditPateintPage(context, list[index]);
                },
                child: Text("编辑", style: TextStyle(fontSize: 16)),
              )
            ],
          ),
        ),
      );
    },
  );
}
